// 引入修改过的 mqttws31-auto.js 文件
let $mqtt = require('@/utils/mqtt/mqttws31.js');

// paho-mqtt connenctOptions 连接配置项
let options = {
	timeout: 1000 * 1000,
	userName: 'admin',
	password: 'admin23',
	useSSL: false, //如果使用 HTTPS 加密则配置为 true
	keepAliveInterval: 10, //心跳
	mqttVersion: 5, //默认为4
	onSuccess: function onConnect() { //success callback function
		console.log('连接成功');
	},
	onFailure: function(message) { //failure callback function
		console.log('连接失败', JSON.stringify(message));
	}
};

let clientId = Math.floor(Math.random() * 10000) + "";

let url = 'wx://120.25.155.46';
let port = 8083;

/* mqtt.Client()的构造方法其实是4个参数
 * url 域名或IP string
 * port 端口 number
 * path 默认是'/mqtt',可以不进行配置 string
 * clientId 这里采用了一个随机数，不能重复 number
 */
let client = new $mqtt.Client(url, port, clientId);

// 当连接丢失/断开时的 callback function
client.onConnectionLost = function onConnectionLost(response) {
	console.log('onConnectionLost', JSON.stringify(response));
};
// 接收到消息 callback function
client.onMessageArrived = function onMessageArrived(message) {
	let payload = message.payloadString;
	let chat = JSON.parse(payload.toString());
	console.log('收到来自', chat.source, '的消息', payload.toString())
	addMessage('home', JSON.parse(payload).content, false)
	saveMsg();
	// console.log('收到保存之后messageAll'+JSON.stringify(messageAll))
};

let messageAll = [];
// business condition 获取缓存
/* uni.getStorage({
    key: 'storage_msg',
    success: function (res) {
        console.log(res.data)
         messageAll= res.data;
    }
}); */

// business condition 用于页面显示
function addMessage(user, content, hasSub, subcontent) {
	messageAll.push({
		user: user,
		content: content,
		hasSub: hasSub,
		subcontent: subcontent
	});
	// console.log(messageAll)
}

// business condition 写入缓存
function saveMsg() {
	// uni.setStorage({
	//  key: 'storage_msg',
	//  data: messageAll,
	//  success: function () {
	//      console.log('消息已存储');
	//      // console.log(messageAll)
	//  }
	// });
}

export {
	client,
	options,
	messageAll,
	addMessage,
	saveMsg
}